import { defineStore } from 'pinia';
import Cookies from 'js-cookie';
import { WebsiteState, WebsiteStates } from './interface';

/**
 * 用户信息
 * @methods setWebInfos 设置用户信息
 */
export const useWebSite = defineStore('webSite', {
	state: (): WebsiteStates => ({
		webSiteInfo: {
			CustomerID: '',
			EntCode: '',
			SiteID: '',
		},
	}),
	actions: {
		async setWebSite(data: WebsiteState | null) {
			if (data == null) {
				this.webSiteInfo = { CustomerID: '', EntCode: '', SiteID: '' };
				Cookies.removeItem('Website');
				localStorage.removeItem('Website');
			} else {
				this.webSiteInfo = data;
				Cookies.set('Website', this.webSiteInfo);
				localStorage.setItem('Website', JSON.stringify(data));
			}
		},

		async getWebSite() {
			if (!this.webSiteInfo || !this.webSiteInfo.SiteID) {
				const websiteLoc = localStorage.getItem('Website');
				if (websiteLoc) {
					const website: any = JSON.parse(websiteLoc);
					this.webSiteInfo = website;
				}
			}

			return this.webSiteInfo;
		},
	},
});
